import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import { Logger } from '../utils/logger.js';
import { ErrorHandler } from '../utils/errorHandler.js';
import { fileTransferMenu } from './fileTransferMenu.js';

export async function connectionMenu(sftpClient, configManager) {
  const configs = configManager.listConfigs();
  const savedConfigs = Object.keys(configs);

  const { connectionType } = await inquirer.prompt([
    {
      type: 'list',
      name: 'connectionType',
      message: '选择连接方式',
      choices: [
        {
          name: '💾 使用保存的配置',
          value: 'saved',
          disabled: savedConfigs.length === 0,
        },
        {
          name: '✏️  手动输入连接信息',
          value: 'manual',
        },
      ],
    },
  ]);

  let config;

  if (connectionType === 'saved') {
    const { configName } = await inquirer.prompt([
      {
        type: 'list',
        name: 'configName',
        message: '选择配置',
        choices: savedConfigs,
      },
    ]);
    config = configs[configName];
  } else {
    config = await getManualConfig(configManager);
    if (!config) return;
  }

  // 验证配置
  const validation = configManager.validateConfig(config);
  if (!validation.valid) {
    Logger.error('配置验证失败:');
    validation.errors.forEach((err) => Logger.error(`  - ${err}`));
    return;
  }

  // 连接
  const spinner = ora('正在连接...').start();
  try {
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    // 进入文件传输菜单
    await fileTransferMenu(sftpClient, configManager, config);
  } catch (error) {
    spinner.fail('连接失败');
    const msg = ErrorHandler.handleConnectionError(error);
    Logger.error(msg);
  } finally {
    await sftpClient.disconnect();
  }
}

async function getManualConfig(configManager) {
  const { host } = await inquirer.prompt([
    {
      type: 'input',
      name: 'host',
      message: '服务器地址 (如: 192.168.1.1)',
      validate: (input) => {
        if (!input) return '服务器地址不能为空';
        return true;
      },
    },
  ]);

  const { port } = await inquirer.prompt([
    {
      type: 'number',
      name: 'port',
      message: 'SSH 端口',
      default: 22,
      validate: (input) => {
        if (input < 1 || input > 65535) return '端口范围应为 1-65535';
        return true;
      },
    },
  ]);

  const { username } = await inquirer.prompt([
    {
      type: 'input',
      name: 'username',
      message: '用户名',
      validate: (input) => {
        if (!input) return '用户名不能为空';
        return true;
      },
    },
  ]);

  const { authType } = await inquirer.prompt([
    {
      type: 'list',
      name: 'authType',
      message: '认证方式',
      choices: [
        { name: '密码认证', value: 'password' },
        { name: '私钥认证', value: 'key' },
      ],
    },
  ]);

  let password, privateKeyPath, passphrase;

  if (authType === 'password') {
    const { pwd } = await inquirer.prompt([
      {
        type: 'password',
        name: 'pwd',
        message: '请输入密码',
        validate: (input) => {
          if (!input) return '密码不能为空';
          return true;
        },
      },
    ]);
    password = pwd;
  } else {
    const { keyPath } = await inquirer.prompt([
      {
        type: 'input',
        name: 'keyPath',
        message: '私钥文件路径',
        validate: (input) => {
          if (!input) return '私钥路径不能为空';
          return true;
        },
      },
    ]);
    privateKeyPath = keyPath;

    const { hasPassphrase } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'hasPassphrase',
        message: '私钥是否需要密码短语?',
        default: false,
      },
    ]);

    if (hasPassphrase) {
      const { phrase } = await inquirer.prompt([
        {
          type: 'password',
          name: 'phrase',
          message: '请输入密码短语',
        },
      ]);
      passphrase = phrase;
    }
  }

  const config = {
    host,
    port,
    username,
    authType,
    password,
    privateKeyPath,
    passphrase,
  };

  const { saveConfig } = await inquirer.prompt([
    {
      type: 'confirm',
      name: 'saveConfig',
      message: '是否保存此配置?',
      default: true,
    },
  ]);

  if (saveConfig) {
    const { configName } = await inquirer.prompt([
      {
        type: 'input',
        name: 'configName',
        message: '配置名称',
        validate: (input) => {
          if (!input) return '配置名称不能为空';
          const configs = configManager.listConfigs();
          if (configs[input]) return '该配置已存在';
          return true;
        },
      },
    ]);
    configManager.saveConfig(configName, config);
  }

  return config;
}
